package com.small.common.base.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.small.common.base.service.BaseService;
import com.small.common.msg.MsgPage;
import com.small.common.config.db.EntityUtils;
import com.small.common.util.Query;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * 通用Service
 *
 * @param <M> dao 接口
 * @param <T> 实体类
 */
public class BaseServiceImpl<M extends Mapper<T>, T> implements BaseService<M, T> {

    @Autowired
    protected M mapper;

    @Autowired
    private EntityUtils entityUtils;

    @Override
    public T selectOne(T entity) {
        return mapper.selectOne(entity);
    }

    @Override
    public T selectById(Object id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<T> selectList(T entity) {
        return mapper.select(entity);
    }

    @Override
    public List<T> selectListAll() {
        return mapper.selectAll();
    }

    @Override
    public int selectCount(T entity) {
        return mapper.selectCount(entity);
    }

    @Override
    public int insert(T entity) {
        entityUtils.setInsertInfo(entity);
        return mapper.insert(entity);
    }

    @Override
    public int insertSelective(T entity) {
        entityUtils.setInsertInfo(entity);
        return mapper.insertSelective(entity);
    }

    @Override
    public int delete(T entity) {
        return mapper.delete(entity);
    }

    @Override
    public int deleteById(Object id) {
        return mapper.deleteByPrimaryKey(id);
    }

    @Override
    public int updateById(T entity) {
        entityUtils.setUpdatedInfo(entity);
        return mapper.updateByPrimaryKey(entity);
    }

    @Override
    public int updateSelectiveById(T entity) {
        entityUtils.setUpdatedInfo(entity);
        return mapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public List<T> selectByExample(Object example) {
        return mapper.selectByExample(example);
    }

    @Override
    public int selectCountByExample(Object example) {
        return mapper.selectCountByExample(example);
    }

    @Override
    public MsgPage<T> selectByQuery(Query query) {
        Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
        Example example = new Example(clazz);
        Example.Criteria criteria = example.createCriteria();
        for (String key : query.keySet()) {
            criteria.andLike(key, "%" + query.get(key).toString() + "%");
        }
        Page<Object> result = PageHelper.offsetPage(query.getOffset(), query.getLimit());
        List<T> list = mapper.selectByExample(example);
        MsgPage<T> page = new MsgPage<T>(list);
        page.setTotal(result.getTotal());
        return page;
    }

}
